import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {UserInfoModel} from '../../../../models/user-info.model';
import {RoleService} from '../../../../service/role.service';
import {Consts} from '../../../../config/consts';

@Component({
  selector: 'app-role-edit',
  templateUrl: './role-edit.component.html',
  styleUrls: ['./role-edit.component.less']
})
export class RoleEditComponent implements OnInit {

  @Input()
  role;
  // 标题
  title;
  // 模态框对象
  formModel: FormGroup;
  roles;
  // 加载
  isOkLoading: boolean;
  @Input()
  isVisible = false;
  @Output()
  emitVisible: EventEmitter<any> = new EventEmitter();
  userInfo: UserInfoModel = new UserInfoModel();

  constructor(
    private roleService: RoleService,
    private fb: FormBuilder) {
    this.userInfo = JSON.parse(sessionStorage.getItem(Consts.USER_INFO));

    this.buildForm();
  }

  ngOnInit(): void {


  }

  ngOnChanges() {
    this.roles = this.userInfo.roles[0].roleId;
    if (this.role != undefined) {
      this.title = '编辑角色';
      this.resetForm(this.role);
    } else {
      this.title = '添加角色';
      this.formModel.reset({
          agencyId: 0,
        }
      );
    }
  }


  buildForm() {
    this.formModel = this.fb.group({
      id: [null, []],
      name: [null, [Validators.required]],
      agencyId: [0, []],
      sort: [null, []],
      desc: [null, []]
    });
  }

  resetForm(role) {
    this.formModel.reset({
      id: role.id,
      name: role.name,
      agencyId: role.agencyId != 0 ? 1 : 0,
      sort: role.sort,
      desc: role.desc
    });
  }

  // 确定修改
  handleOk(): void {
    this.isOkLoading = true;

    // 校验非空和其他非法输入
    if (!this.roleService.zorro.validateFormValidate(this.formModel)) {
      return;
    }

    if (!this.isOkLoading) {
      return;
    }

    // 私有角色就是上级机构号
    if (this.formModel.value.agencyId == 1) {
      this.formModel.value.agencyId = this.userInfo.agencyId;
    }

    if (this.role != undefined) {
      this.roleService.updateRole(this.formModel.value, res => {
        this.commonHandle();
      });
    } else {
      this.roleService.addRole(this.formModel.value, res => {
        if (res.status == 0) {
          this.roleService.layer.messageSuccess(res.msg);
          this.commonHandle();
        } else {
          this.roleService.layer.notificationError(res.msg);
        }
      });
    }
  }

  // 取消修改
  handleCancel(): void {
    this.isVisible = false;
    let body = {'cancel': true, 'isVisible': this.isVisible};
    this.emitVisible.emit(body);
  }

  commonHandle() {
    this.isOkLoading = false;
    this.isVisible = false;
    let body = {'isVisible': this.isVisible};
    this.emitVisible.emit(body);
  }

}
